﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using CopyFolder.Properties;
using Ait = Authorit.API;
using AitEx = AuthoritExtensibility;
using Authorit.API.Utilities;

namespace CopyFolder
{
    public partial class FolderSelector : Form
    {
        #region Fields (8)
        private Ait.ApplicationContext appContext;
        private Ait.Services.Authentication authService;
        private Ait.Services.Permissions permsService;
        private bool copyReleaseStates;
        private Ait.Services.Folder folderService;
        private Ait.Services.Library libraryService;
        private String libraryName;
        private int targetFolderId;
        private ImageList treeImages;
        private AitEx.AuthoritEventArgs aitArgs;
        #endregion Fields 

        #region Constructors (1) 

        public FolderSelector()
        {
            InitializeComponent();
        }

        #endregion Constructors 

        #region Properties (7) 

        public bool CopyReleaseStates
        {
            get { return copyReleaseStates; }
        }

        public AitEx.AuthoritEventArgs AitEventArgs
        {
            get { return this.aitArgs; }
            set { this.aitArgs = value; }
        }

        public int TargetFolderId
        {
            get { return targetFolderId; }
            set { targetFolderId = value; }
        }

        #endregion Properties 

        #region Methods (7) 

        // Private Methods (7) 

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Windows.Forms.TreeNode.set_ImageKey(System.String)")]
        private void AddChildNodes(ref TreeNode rootNode, int folderId)
        {
            Ait.Dto.LoginResponse response = new Ait.Dto.LoginResponse();
            if (!authService.IsLoggedIn())
            {
                response = authService.Login(appContext.LibrariesConfiguration[0].Alias, aitArgs.Username, aitArgs.Password);
            }
            if (response.Result == Ait.Dto.LoginResult.Success)
            {
                Stack<int> folders = new Stack<int>();
                folders.Push(folderId);
                while (folders.Count > 0)
                {
                    folderId = folders.Pop();
                    List<Ait.Dto.Folder> childFolders = (List<Ait.Dto.Folder>)folderService.GetChildren(folderId);
                    for (int i = 0; i < childFolders.Count; i++)
                    {
                        TreeNode newNode = new TreeNode(childFolders[i].Name);
                        newNode.ToolTipText = String.Format(System.Globalization.CultureInfo.CurrentCulture, Resources.FolderNodeTooltip, childFolders[i].Name);
                        newNode.ImageKey = "FolderClosed";
                        newNode.SelectedImageKey = "FolderClosedSelected";
                        newNode.Tag = childFolders[i];
                        newNode.Name = childFolders[i].FolderId.ToString(System.Globalization.CultureInfo.CurrentCulture);
                        if (childFolders[0].ParentFolderId != 0)
                        {
                            TreeNode[] foundNodes = rootNode.Nodes.Find(childFolders[i].ParentFolderId.ToString(System.Globalization.CultureInfo.InvariantCulture), true);
                            foreach (TreeNode node in foundNodes)
                            {
                                if (((Ait.Dto.Folder)node.Tag).FolderId == childFolders[i].ParentFolderId)
                                {
                                    node.Nodes.Add(newNode);
                                }
                            }
                        }
                        else
                        {
                            rootNode.Nodes.Add(newNode);
                        }
                        folders.Push(childFolders[i].FolderId);
                    }
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (permsService.CheckPermissionsForFolder(targetFolderId, Ait.Dto.Permission.List | Ait.Dto.Permission.ModifyFolders | Ait.Dto.Permission.Read | Ait.Dto.Permission.Write | Ait.Dto.Permission.ChangeReleaseState))
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show(Resources.InsufficientFolderPermissionsMessage, Resources.InsufficientFolderPermissionsTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void chkCopyReleaseStates_CheckedChanged(object sender, EventArgs e)
        {
            this.copyReleaseStates = chkCopyReleaseStates.Checked;
        }

        private void FolderSelector_Load(object sender, EventArgs e)
        {
            LoadProperties();
            Initialize_AuthoritServices();
            Ait.Dto.LoginResponse response = new Ait.Dto.LoginResponse();
            if (!authService.IsLoggedIn())
            {
                response = authService.Login(appContext.LibrariesConfiguration[0].Alias, aitArgs.Username, aitArgs.Password);
            }
            if (response.Result == Ait.Dto.LoginResult.Success)
            {
                Ait.Dto.LibraryInformation libInfo = libraryService.GetInformation();
                this.libraryName = libInfo.Name;
                TreeNode rootNode = new TreeNode(this.libraryName);
                rootNode.ImageKey = "Library";
                rootNode.SelectedImageKey = "LibrarySelected";
                AddChildNodes(ref rootNode, 0);
                treeView1.Nodes.Add(rootNode);
                treeView1.Nodes[0].Expand();
                treeView1.SelectedNode = null;
            }
        }

        private void Initialize_AuthoritServices()
        {
            appContext = PluginUtility.GetAppContext(this.aitArgs);
            folderService = appContext.GetServiceInstance<Ait.Services.Folder>();
            authService = appContext.GetServiceInstance<Ait.Services.Authentication>();
            permsService = appContext.GetServiceInstance<Ait.Services.Permissions>();
            libraryService = appContext.GetServiceInstance<Ait.Services.Library>();
        }

        private void LoadProperties()
        {
            this.Text = Resources.FolderSelectorFormTitle;
            this.Icon = Resources.CopyFolderIcon;
            btnCancel.Text = Resources.BtnCancel;
            btnOk.Text = Resources.BtnOkText;
            chkCopyReleaseStates.Text = Resources.CopyReleaseStatesLabel;
            toolTip1.ToolTipIcon = Settings.Default.FolderSelectorTooltipIcon;
            toolTip1.UseAnimation = Settings.Default.FolderSelectorTooltipUseAnimation;
            toolTip1.UseFading = Settings.Default.FolderSelectorTooltipUseFading;
            toolTip1.SetToolTip(chkCopyReleaseStates, Resources.CopyReleaseStatesTooltip);
            chkCopyReleaseStates.Checked = Settings.Default.CopyReleaseStateDefault;
            this.copyReleaseStates = chkCopyReleaseStates.Checked;
            treeImages = new ImageList();
            treeImages.Images.Add("Library", Resources.Library);
            treeImages.Images.Add("LibrarySelected", Resources.LibrarySelected);
            treeImages.Images.Add("FolderClosed", Resources.FolderClosed);
            treeImages.Images.Add("FolderOpen", Resources.FolderOpen);
            treeImages.Images.Add("FolderClosedSelected", Resources.FolderClosedSelected);
            treeImages.Images.Add("FolderOpenSelected", Resources.FolderOpenSelected);
            treeView1.ImageList = treeImages;
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            this.btnOk.Enabled = true;
            if (e.Node.Parent == null)
            {
                this.targetFolderId = 0;
            }
            else
            { 
                this.targetFolderId = ((Ait.Dto.Folder)e.Node.Tag).FolderId;
            }
        }

        #endregion Methods 

        private void FolderSelector_Shown(object sender, EventArgs e)
        {
            this.Focus();
            treeView1.SelectedNode = null;
        }
    }
}
